from flask import Flask, g, jsonify
from flask_auth_mgr import AuthMgr

#--------------------#
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
auth = AuthMgr(app.config['SECRET_KEY'])

#--------------------#
users = {
    "john": auth.generate_password_hash("hello"),
    "susan": auth.generate_password_hash("bye")
}

#--------------------#
@auth.basic.verify_password
def verify_password(user, password):
    g.user = None
    if user not in users:
        return False
    if auth.check_password_hash(users.get(user), password):
        g.user = user
        return True
    return False

@auth.rftoken.verify_token
def verify_rftoken(token):
    data = auth.rftoken_data(token)
    if data is None:
        return False
    g.user = data['user']
    return True

@auth.atoken.verify_token
def verify_atoken(token):
    data = auth.atoken_data(token)
    if data is None:
        return False
    g.user = data['user']
    return True
#--------------------#
@app.route('/refresh_token')
@auth.basic.login_required
def route_refresh_token():
    token_data = {
        'user': g.user,
    }

    data = {
        'refresh_token': auth.generate_rftoken(token_data),
    }
    return jsonify(data)

@app.route('/access_token')
@auth.rftoken.login_required
def route_access_token():
    token_data = {
        'user': g.user,
    }

    data = {
        'access_token': auth.generate_atoken(token_data),
    }
    return jsonify(data)

# rftoken -> rftoken
@app.route('/token')
@auth.rfmulti.login_required
def route_token():
    token_data = {
        'user': g.user,
    }

    data = {
        'refresh_token': auth.generate_rftoken(token_data),
        'access_token': auth.generate_atoken(token_data),
    }
    return jsonify(data)
#--------------------#
@app.route('/need_pwd')
@auth.basic.login_required
def route_need_pwd():
    return 'this page need password: %s\n' % g.user

@app.route('/need_rftoken')
@auth.rftoken.login_required
def route_need_rftoken():
    return 'this page need refresh token: %s\n' % g.user

@app.route('/need_pwd_rftoken')
@auth.rfmulti.login_required
def route_need_pwd_rftoken():
    return 'this page need password or refresh token: %s\n' % g.user

@app.route('/need_atoken')
@auth.atoken.login_required
def route_need_atoken():
    return 'this page need access token: %s\n' % g.user

@app.route('/need_pwd_atoken')
@auth.amulti.login_required
def route_need_pwd_atoken():
    return 'this page need password or access token: %s\n' % g.user
#--------------------#

if __name__ == '__main__':
    app.run(debug=True)
#--------------------#
